import { material, project } from '@alilc/lowcode-engine';
import { filterPackages } from '@alilc/lowcode-plugin-inject';
import { Message, Dialog } from '@alifd/next';
import { IPublicTypeProjectSchema, IPublicEnumTransformStage } from '@alilc/lowcode-types';
import DefaultPageSchema from './defaultPageSchema.json';
import DefaultI18nSchema from './defaultI18nSchema.json';
import axios from 'axios';
const generateProjectSchema = (pageSchema: any, i18nSchema: any): IPublicTypeProjectSchema => {
  return {
    componentsTree: [pageSchema],
    componentsMap: material.componentsMap as any,
    version: '1.0.0',
    i18n: i18nSchema,
  };
};

/**
 * 保存表单schema 到本地
 * @param scenarioName
 */
export const saveSchema = async (scenarioName: string = 'unknown') => {
  setProjectSchemaToLocalStorage(scenarioName);
  await setPackagesToLocalStorage(scenarioName);
  Message.success('成功保存');
};

export const resetSchema = async (scenarioName: string = 'unknown') => {
  try {
    await new Promise<void>((resolve, reject) => {
      Dialog.confirm({
        content: '确定要重置吗？您所有的修改都将消失！',
        onOk: () => {
          resolve();
        },
        onCancel: () => {
          reject();
        },
      });
    });
  } catch (err) {
    return;
  }
  const defaultSchema = generateProjectSchema(DefaultPageSchema, DefaultI18nSchema);

  project.importSchema(defaultSchema as any);
  project.simulatorHost?.rerender();

  setProjectSchemaToLocalStorage(scenarioName);
  await setPackagesToLocalStorage(scenarioName);
  Message.success('成功重置页面');
};

const getLSName = (scenarioName: string, ns: string = 'projectSchema') => `${scenarioName}:${ns}`;

/**
 * 从本地缓存读取schema
 * @param scenarioName
 */
export const getProjectSchemaFromLocalStorage = (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return Promise.reject(new Error('scenarioName is required!'));
  }
  // 调用接口 来保存 exportSchemaJson,接口url:http://127.0.0.1:8080/palm/orgFormSchema/get.json?corpId=ding123&scenarioName=form22
  // 求参数格式使用标准的form-data格式
  const urlParams = new URLSearchParams(window.location.search);
  const corpId = urlParams.get('corpId');
  if (window.previewmock) {
    console.log('getProjectSchemaFromLocalStorage,scenarioName:' + scenarioName + ',schema:null');
    const localValue = window.localStorage.getItem(getLSName(scenarioName));
    console.log(
      'getProjectSchemaFromLocalStorage,scenarioName:' + scenarioName + ',schema:' + localValue,
    );
    if (localValue) {
      return JSON.parse(localValue);
    }
    return undefined;
  }
  return axios
    .post(
      window.orgFormSchemaIp + '/palm/orgFormSchema/get.json',
      new URLSearchParams({
        corpId: corpId || 'ding123',
        scenarioName: scenarioName,
        justSchema: 'true',
      }),
    )
    .then((response) => {
      // debugger
      console.log(
        'getProjectSchemaFromLocalStorage,scenarioName:' +
          scenarioName +
          ',schema:' +
          response.data,
      );
      return response.data;
      // window.localStorage.setItem(getLSName(scenarioName), JSON.stringify(response.data));
    })
    .catch((error) => {
      console.error('getProjectSchemaFromLocalStorage error:', error);
      return undefined;
    });
};
/**
 * 保存表单schema 到本地
 * @param scenarioName
 */
const setProjectSchemaToLocalStorage = (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return;
  }
  const exportSchemaJson = JSON.stringify(project.exportSchema(IPublicEnumTransformStage.Save));
  console.log(
    'setProjectSchemaToLocalStorage2,scenarioName' +
      scenarioName +
      ',exportSchemaJson:' +
      exportSchemaJson,
  );

  // 调用接口 来保存 exportSchemaJson,接口url:http://127.0.0.1:8080/palm/orgFormSchema/save.json?corpId=ding123&scenarioName=form22&schemaJson=%7Bschema444%7D
  // 使用reactjs axios 实现
  // 把下面的请求参数格式改为标准的form-data格式
  // axios.post('http://127.0.0.1:8080/palm/orgFormSchema/save.json', new URLSearchParams({
  //   corpId: 'ding123',
  //   scenarioName: scenarioName,
  //   schemaJson: exportSchemaJson,
  // }));
  const urlParams = new URLSearchParams(window.location.search);
  const corpId2 = urlParams.get('corpId');
  axios
    .post(
      window.orgFormSchemaIp + '/palm/orgFormSchema/save.json',
      new URLSearchParams({
        corpId: corpId2 || 'ding123',
        scenarioName: scenarioName,
        schemaJson: exportSchemaJson,
      }),
    )
    .then((res) => {
      console.log('saveSchema success', res);
    })
    .catch((err) => {
      console.error('saveSchema error', err);
    });
  // 存储到本地
  window.localStorage.setItem(getLSName(scenarioName), exportSchemaJson);
};

/**
 * see saveSchema
 * @param scenarioName
 */
const setPackagesToLocalStorage = async (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return;
  }
  const packages = await filterPackages(material.getAssets().packages);
  let formSchema = JSON.stringify(packages);
  // console.log('setPackagesToLocalStorage,scenarioName'+scenarioName+",packages:"+formSchema);
  window.localStorage.setItem(getLSName(scenarioName, 'packages'), formSchema);
};

export const getPackagesFromLocalStorage = (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return;
  }
  return JSON.parse(window.localStorage.getItem(getLSName(scenarioName, 'packages')) || '{}');
};

export const getProjectSchema = async (
  scenarioName: string = 'unknown',
): Promise<IPublicTypeProjectSchema> => {
  const pageSchema = await getPageSchema(scenarioName);
  // debugger
  return generateProjectSchema(pageSchema, DefaultI18nSchema);
};
/**
 * 获取 page schema,从本地缓存读取schema
 * @param scenarioName
 */
export const getPageSchema = async (scenarioName: string = 'unknown') => {
  const schemaJson = await getProjectSchemaFromLocalStorage(scenarioName);
  const pageSchema = schemaJson?.componentsTree?.[0];
  // debugger
  if (pageSchema) {
    return pageSchema;
  }

  return DefaultPageSchema;
};

export const getPreviewLocale = (scenarioName: string) => {
  const key = getLSName(scenarioName, 'previewLocale');
  return window.localStorage.getItem(key) || 'zh-CN';
};

export const setPreviewLocale = (scenarioName: string, locale: string) => {
  const key = getLSName(scenarioName, 'previewLocale');
  window.localStorage.setItem(key, locale || 'zh-CN');
  window.location.reload();
};
